<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>订单详情</span>
        <el-button-group style="float: right;">
          <el-button
            type="primary"
            icon="el-icon-edit"
            class="el-button--medium"
            @click="handleCreate"
            >工序报工</el-button
          >
        </el-button-group>
      </div>

      <el-row type="flex" justify="start">
        <el-table
          v-loading="listLoading"
          :data="list2"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          @row-click="rowClick"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" label="序号" width="95" v-if="false">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="订单编号"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.orderNo }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="产品编号"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.productNo }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="产品名称"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.productName }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工序编号"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.procedureNo }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工序名称"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.procedureName }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="批次"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.batch }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="客户需求量"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.totalAmount }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="已生产数量"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.producedAmount }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="未生产数量"
            width="95"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.planAmount }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="最新报工时间"
            width="120"
            style="display:none;"
          >
            <template slot-scope="scope">
              {{ scope.row.lastReportDate }}
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <pagination
          v-show="total2 > 0"
          :total="total2"
          :page.sync="listQuery2.page"
          :limit.sync="listQuery2.limit"
          :page-sizes="listQuery2.pageSizes"
          @pagination="fetchData"
        />
      </el-row>
    </el-card>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="80%"
    >
      <el-row type="flex" justify="start">
        <el-col :span="24">
          <el-table
            v-loading="listLoading"
            :data="listSon"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            class="tb-edit"
            @selection-change="handleSelectionChangeSon"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="序号"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="订单编号"
              width="95"
              style="display:none;"
            >
              <template scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.orderNo"
                  placeholder="请输入内容"
                  @change="handleEdit(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.orderNo }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.productNo"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.productNo }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.productName"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.productName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.procedureNo"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.procedureNo }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.procedureName"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.procedureName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="批次"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.batch"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.batch }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="客户需求量"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.amount"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="最新报工时间"
              width="120"
              style="display:none;"
            >
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.reportDate"
                  placeholder="请输入内容"
                  @change="ui_update(scope.$index, scope.row)"
                ></el-input>
                <span>{{ scope.row.reportDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <span
                  class="el-tag el-tag--info el-tag--mini"
                  style="cursor: pointer;"
                  @click="ui_update(scope.row, scope.$index, true)"
                >
                  {{ scope.row.isSet ? "保存" : "修改" }}
                </span>
                <span
                  v-if="!scope.row.isSet"
                  class="el-tag el-tag--danger el-tag--mini"
                  style="cursor: pointer;"
                  @click="ui_delete(scope.row, scope.$index)"
                >
                  删除
                </span>
                <span
                  v-else
                  class="el-tag  el-tag--mini"
                  style="cursor: pointer;"
                  @click="ui_update(scope.row, scope.$index, false)"
                >
                  取消
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24">
          <div class="el-table-add-row" style="width: 99.2%;" @click="addRow()">
            <span>+ 添加</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          :page-sizes="listQuery.pageSizes"
          @pagination="fetchDataSon"
        />
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch
} from "@/api/produce/ProduceDayReportApi";

import {
  getAll as getAllSon,
  getList as getListSon,
  create as createSon,
  update as updateSon,
  deleteBatch as deleteBatchSon
} from "@/api/produce/ProduceDayReportDetailApi";

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      data2: [],
      list2: [],
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentProduceDayReportTypeId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rulesson: {
        orderNo: [
          {
            required: true,
            message: "订单编号不能为空！",
            trigger: "change"
          }
        ],
        productNo: [
          {
            required: true,
            message: "产品编号不能为空！",
            trigger: "change"
          }
        ],
        productName: [
          {
            required: true,
            message: "产品名称不能为空！",
            trigger: "change"
          }
        ],
        procedureNo: [
          {
            required: true,
            message: "工序编号不能为空！",
            trigger: "change"
          }
        ],
        procedureName: [
          {
            required: true,
            message: "工序名称不能为空！",
            trigger: "change"
          }
        ],
        batch: [
          {
            required: true,
            message: "批次不能为空！",
            trigger: "change"
          }
        ],
        totalAmount: [
          {
            required: true,
            message: "客户需求量不能为空！",
            trigger: "change"
          }
        ],
        producedAmount: [
          {
            required: true,
            message: "已生产数量不能为空！",
            trigger: "change"
          }
        ],
        planAmount: [
          {
            required: true,
            message: "未生产数量不能为空！",
            trigger: "change"
          }
        ],
        lastReportDate: [
          {
            required: true,
            message: "最新报工时间不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        procedureNo: "",
        procedureName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        lastReportDate: ""
      },
      tempSon: {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        procedureNo: "",
        procedureName: "",
        batch: "",
        amount: "",
        reportDate: ""
      },
      //表格變量
      lstSelected: [],
      listSon: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      lstSelectedSon: []
    };
  },
  watch: {},
  computed: {},
  created() {
    this.fetchData();
    this.fetchDataSon();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
      const type = this.listSon.find(v => v.therbligsNo === val.therbligsNo);
      if (type != null) {
        this.currentProduceDayReportTypeId = type.id;
      }
    },
    fetchData() {
      let params = {
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      return getList(params).then(response => {
        this.list2 = response.data.records;
        console.log(this.list2);
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    fetchDataSon() {
      let params = {
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      return getListSon(params).then(response => {
        this.listSon = response.data.records;
        if (this.getListSon != null && this.listSon.length > 0) {
          this.listSon.map(v => {
            v.isSet = false;
          });
        }
        this.total = response.data.total;
        this.listLoading = false;
        
      });
    },
    rowClick(row, column, event) {
      this.currentProduceDayReportTypeId = row.id;
      this.fetchData();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        procedureNo: "",
        procedureName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        lastReportDate: ""
      };
    },
    resetTempSon() {
      this.tempSon = {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        procedureNo: "",
        procedureName: "",
        batch: "",
        amount: "",
        reportDate: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataFormson"].clearValidate();
      // });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length !== 1) {
        this.$message.error("请先选择一条日报工记录");
        return;
      }
      this.tempson = Object.assign({}, this.lstSelected[0]); // copy obj
      debugger;
      this.tempson.therbligsTypeId = this.currentTherbligsTypeId;
      this.tempson = { ...this.tempson };
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    ui_create() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          this.tempson.id = 0; //自增
          create(this.tempson).then(() => {
            this.list2.unshift(this.tempson);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update(row, index, cg) {
      debugger;
      //点击修改 判断是否已经保存所有操作
      for (let i of this.listSon) {
        if (i.isSet && i.id != row.id) {
          this.$message.warning("请先保存当前编辑项");
          return false;
        }
      }
      //是否是取消操作
      if (!cg) {
        if (!this.listSon.sel.id) this.listSon.splice(index, 1);
        return (row.isSet = !row.isSet);
      }
      //提交数据
      if (row.isSet) {
        //如果是新增
        if (row.id == null) {
          row.id = 0;
        }
        updateSon(row).then(() => {
          const index = this.listSon.findIndex(v => v.id === row.id);
          this.listSon.splice(index, 1, row);
          this.dialogFormVisible = false;
          this.$notify({
            title: "Success",
            message: "修改成功！",
            type: "success",
            duration: 2000
          });
          this.fetchData();
        });
      } else {
        this.listSon.sel = JSON.parse(JSON.stringify(row));
        row.isSet = true;
      }
    },
    ui_delete(row, index) {
      this.$confirm("此操作将删除此工序报工数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          debugger
          let ids = [];
          ids.push(row.id);
          deleteBatchSon(ids).then(() => {
            ids.forEach(elm => {
              const index = this.listSon.findIndex(v => v.id === elm);
              this.listSon.splice(index, 1);
            });
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "删除成功！",
              type: "success",
              duration: 2000
            });
          });
        })
        .catch(() => {
          //点击取消的提示
        });
    },
    handleMainTypeChange(val) {
      this.tempson.produceDayReportTypeId = val;
      this.tempson = { ...this.tempson };
    },
    addRow() {
      this.resetTempSon();
      this.listSon.push(this.tempSon);
    },
    handleSelectionChangeSon(val) {
      this.lstSelectedSon = val;
    }
  }
};
</script>
<style>
.tb-edit .el-input {
  display: none;
}
.tb-edit .current-row .el-input {
  display: block;
}
.tb-edit .current-row .el-input + span {
  display: none;
}
.el-table-add-row {
  margin-top: 10px;
  width: 100%;
  height: 34px;
  border: 1px dashed #c1c1cd;
  border-radius: 3px;
  cursor: pointer;
  justify-content: center;
  display: flex;
  line-height: 34px;
}
</style>
